//axios二次封装
//create创建：创建axios实例，配置基础路径和超时时间
import axios from 'axios'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user.ts'
const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000
})
//请求拦截器
request.interceptors.request.use(config => {
  // 引入pinia拿到token携带上
  let userStore = useUserStore()
  config.headers.token = userStore.token
  //请求头+公共参数
  return config
})
//响应拦截器
request.interceptors.response.use(
  //成功->返回简化回调
  res => {
    return res.data
  },
  //失败
  //处理http网络错误
  err => {
    let msg = ''
    let code = err.response.status
    switch (code) {
      case 401:
        msg = 'Token过期'
        break
      case 403:
        msg = '无权访问'
        break
      case 404:
        msg = '请求地址错误'
        break
      case 500:
        msg = '服务器出现错误'
        break
      default:
        msg = '网络有问题'
        break
    }
    ElMessage({
      type: 'error',
      message: msg
    })
    return Promise.reject(err)
  }
)
export default request
